package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.result.Result;
import com.sky.service.ShoppingCartService;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/shoppingCart")
@Api(tags = "C端购物车接口")
public class ShoppingCartController {
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private AliOssUtil aliOssUtil;

    private Long currentId;
    @PostMapping("/add")
    @ApiOperation("添加购物车")
    public Result<String> add(@RequestBody ShoppingCartDTO shoppingCartDTO){
        currentId = BaseContext.getCurrentId();
        shoppingCartService.add(shoppingCartDTO,currentId);
        return Result.success();
    }
    @GetMapping("/list")
    @ApiOperation("查看购物车")
    public Result<List<ShoppingCart>> list(){
        String key = "shoppingCart::"+BaseContext.getCurrentId();
        //先从redis中获取
        List<ShoppingCart> shoppingCartList = (List<ShoppingCart>) redisTemplate.opsForValue().get(key);
        if (shoppingCartList == null || shoppingCartList.isEmpty()){
            shoppingCartList = shoppingCartService.list();
            redisTemplate.opsForValue().set(key,shoppingCartList);
            //设置7天过期
            redisTemplate.expire(key,7, TimeUnit.DAYS);
        }
        for (ShoppingCart shoppingCart : shoppingCartList) {
            shoppingCart.setImage(aliOssUtil.generatePresignedUrl(shoppingCart.getImage()));
        }
        return Result.success(shoppingCartList);

    }
    //清空购物车
    @DeleteMapping("/clean")
    @ApiOperation("清空购物车")
    public Result<String> clean(){
        currentId = BaseContext.getCurrentId();
        shoppingCartService.clean(currentId);
        return Result.success();
    }
    @PostMapping("/sub")
    @ApiOperation("删除购物车中的某一个商品")
    public Result<String> sub(@RequestBody ShoppingCartDTO shoppingCartDTO){
        currentId = BaseContext.getCurrentId();
        shoppingCartService.sub(shoppingCartDTO,currentId);
        return Result.success();
    }
}
